package com.intellif.mozping.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author by mozping
 * @Classname MyThreadPool
 * @Description 手写线程池
 * @Date 2019/1/5 17:24
 */
public class MyThreadPool {

    //线程池默认的线程数
    private static int WORK_THREAD_NUM = 5;
    //保存任务的队列
    private static int MAX_TASK_NUM = 100;

    //任务队列
    private static final BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(MAX_TASK_NUM);
    //线程数量
    private int workNum;
    //线程数组
    Worker[] workers;

    public MyThreadPool(int workNum) {
        if (workNum <= 0 || workNum >= 10) {
            this.workNum = WORK_THREAD_NUM;
        } else {
            this.workNum = workNum;
        }
        workers = new Worker[5];
        for (int i = 0; i < this.workNum; i++) {
            workers[i] = new Worker();
            workers[i].start();
        }
    }

    public void shutDown() {
        for (int i = 0; i < workNum; i++) {
            ((Worker) workers[i]).shutDown();
        }
    }


    static class Worker extends Thread {

        Runnable take = null;

        @Override
        public void run() {
            while (isInterrupted()) {
                try {
                    take = blockingQueue.take();
                    if (take != null) {
                        take.run();
                    }
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    System.out.println("线程 " + Thread.currentThread().getName() +
                            " 捕获到了中断异常，开始清理工作...");
                    System.out.println("线程 " + Thread.currentThread().getName() +
                            "可以安全的终止退出了...");
                    return;
                }
            }
        }

        public void shutDown() {
            interrupt();
        }
    }

    public void submit(Runnable runnable) {
        if (runnable == null) {
            throw new NullPointerException();
        }
        try {
            blockingQueue.add(runnable);
        } catch (IllegalStateException e) {
            throw e;
        }
    }

}
